import { commonReduxGenerator } from 'utils/reduxGenerator/index'
import _ from 'lodash'
import moment from 'moment'
import store from 'store'
import axios from 'axios'

import { url, api } from 'config/api'

const input_building_info = 'input_building_info'

// 用户系统时间与服务器时间允许的最大差值 单位毫秒
// const LimitDiffTime = 5 * 1000
const LimitDiffTime = 60 * 1000

// 楼盘信息
export const {
  reducer,

  success,
  error,
  reset,
  loading,
  loaded
} = commonReduxGenerator({
  type: 'building',

  state: {
    // 楼盘id
    propertyId: '',
    // 楼盘期数id
    housePreiodId: '',
    // 楼盘名称
    propertyName: '',

    /**
     * [payWay 支付方式]
     * @type {String}
     *       1: pos收款 (二维码)
     *       2: 线下收款
     *       3: 线上收款 (在线支付)
     */
    payWay: '',

    // 系统当前时间
    currentDate: '',
    // 备选开始时间
    preSelectDate: '',
    // 备选结束时间
    preSelectEndDate: '',
    // 开盘开始时间
    hobSpecificTime: '',
    // 开盘结束时间
    hobSpecificEndTime: '',
    // 办理截止时间
    manageEndDate: '',

    // 开盘说明
    backup1: '',

    query: {}
  },

  action: [{
    action: input_building_info,
    result: (state, payload) => {
      return {
        ...state,
        ...payload
      }
    }
  }]
})

export function inputBuildingInfo (payload) {
  const building = store.get('building') || {}

  // 缓存起
  store.set('building', {
    // ...building,
    ...payload
  })

  return {
    payload,
    type: input_building_info
  }
}

export function getBuilding (params = {}, ignoreCache) {
  return async (dispatch, getState) => {
    const {
      building: {
        loading: _loading,
        msg,
        init,
        query,

        ...rest
      }
    } = getState()

    if (_loading) {
      return ['重复请求']
    }

    if (init && !ignoreCache && _.isEqual(params, query)) {
      return [null, rest]
    }

    dispatch(loading())


    const sendDate = (new Date()).getTime()

    const [err, res] = await axios.post(url.server + api.getBuilding, params)

    const receiveDate = (new Date()).getTime()

    dispatch(loaded())

    if (err) {
      dispatch(error(err))

      return [err]
    }

    const {
      data
    } = res

    if (!_.isPlainObject(data)) {
      dispatch(error('服务器未返回正确的数据'))

      return ['服务器未返回正确的数据']
    }

    const {
      propertyId,

      currentDate,
      preSelectDate,
      preSelectEndDate,
      hobSpecificTime,
      hobSpecificEndTime,

      backup1,
    } = data

    if (!propertyId) {
      dispatch(error('服务器未返回[propertyId]'))

      return ['服务器未返回[propertyId]']
    }

    if (currentDate) {
      const diffTime = Math.abs(moment().subtract(receiveDate - sendDate, 'ms').diff(moment(currentDate && currentDate.time ? currentDate.time : currentDate)))

      if (diffTime > LimitDiffTime) {
        dispatch(success({
          ...data,
          preSelectEndDate: preSelectEndDate ? preSelectEndDate : hobSpecificTime
        }))

        dispatch(error(`本地时间与服务器时间差异过大(${ diffTime })`))

        return [`本地时间与服务器时间差异过大(${ diffTime })`]
      }
    }

    dispatch(success({
      ...data,
      preSelectEndDate: preSelectEndDate ? preSelectEndDate : hobSpecificTime,
      query: params
    }))

    return [null, data]
  }
}
